package com.zr.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import net.sf.json.JSONObject;

/**
 * 处理打印用户信息请求
 * @author lzq
 *
 */
public class PrintUserMsgAction extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		String[] unames = req.getParameterValues("unames[]");
		String[] rnames = req.getParameterValues("rnames[]");
		String file = req.getParameter("file");
		boolean b = printUserMsg(unames, rnames, file);
		PrintWriter pw = resp.getWriter();
		JSONObject json = new JSONObject();
		if(b){
			json.put("success", true);
			json.put("msg", "导出成功!");
		}else{
			json.put("success", false);
			json.put("msg", "导出失败!");
		}
		pw.write(json.toString());
		pw.flush();
	}
	
	/**
	 * 进行用户信息的导出
	 * @param unames	用户名集合
	 * @param rnames	用户角色集合
	 */
	private boolean printUserMsg(String[] unames,String[] rnames,String file){
		File f = new File("C:\\Users\\Administrator\\Desktop\\"+file+".xlsx");
		try {
			f.createNewFile();
			Workbook workbook = new HSSFWorkbook();
			Sheet sheet = workbook.createSheet("用户信息表一");
			Row row = sheet.createRow(0);
			row.createCell(0).setCellValue("用户名");
			row.createCell(1).setCellValue("角色名");
			
			for (int i = 0; i < unames.length; i++) {
				row = sheet.createRow(i+1);
				row.createCell(0).setCellValue(unames[i]);
				row.createCell(1).setCellValue(rnames[i]);
			}
			FileOutputStream out = new FileOutputStream(f);
			workbook.write(out);
			out.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
}
